package com.ruoyi.web.utils;

import com.ruoyi.common.enums.DataTypeEnum;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.Map;

public class WordUtils {

    public static WordUtils creater(){
        return new WordUtils();
    }

    public String exportWord(HttpServletResponse response, Map<String, Object> dataMap, DataTypeEnum fileEnum) {
        InputStream inputStream = null;
        ServletOutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
            Template template = configuration.getTemplate(fileEnum.getTemplateName(), "utf-8");

            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileEnum.getFileName())
                            + ";filename*=utf-8''" + URLEncoder.encode(fileEnum.getFileName()));
            out = response.getOutputStream();
            bos = new BufferedOutputStream(out);

            Writer writer = new BufferedWriter(new OutputStreamWriter(bos, "UTF-8"));

            template.process(dataMap, writer);
            out.flush();
            out.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }finally {
            if (null != out) {
                try {
                    //最后别忘记了关闭流
                    out.close();
                } catch (IOException e) {
                }
            }
            if (null != bos) {
                try {
                    //最后别忘记了关闭流
                    bos.close();
                } catch (IOException e) {
                }
            }
            if (null != inputStream) {
                try {
                    //最后别忘记了关闭流
                    inputStream.close();
                } catch (IOException e) {
                }
            }

        }
        return "success";

    }

}
